import store from '@/store'
import router from '@/router'
class Websocket {
	constructor(url) {
		this.url = url;
		this.ws = ''
		this.reconnect = false //是否连接
		this.infoData = null
	}
	// 连接
	connect() {
		this.ws = new WebSocket(this.url);
		this.ws.onopen = () => {
			this.reconnect = true
			if (this.infoData != null) {
				this.ws.send(this.infoData);
			} else {
				this.connect()
			}
		};
		this.ws.onmessage = (res) => {
			// console.log('获取消息', res.data);
			var obj = JSON.parse(res.data)
			// console.log('获取消息', obj);
			if (obj.code == 1) {
				store.dispatch('GETWEBSOCKLIST', obj);

			} else if (obj.code == '-1') {
				this.reconnect = false
				this.ws.onclose()
				store.dispatch('LOGOUT')
				router.push('/login')
			}
		};
		this.ws.onclose = () => {
			console.log('关闭了 重新连接')
			if (this.infoData != null && this.reconnect) {
				setTimeout(() => {
					this.connect()
				}, 5000)
			}
		};
		this.ws.onerror = (error) => {
			this.ws.onclose()
			if (this.infoData != null && this.reconnect) {
				setTimeout(() => {
					this.connect()
				}, 5000)
			}
		};
	}
	// 处理语言
	SetLang(Lang) {
		let lang = Lang
		let langCode = ''
		if (lang == 'zhtw') {
			langCode = 'zh-tw'
		} else {
			langCode = 'zh'
		}
		return langCode
	}
	// 发送
	send(data) {
		data.lang=this.SetLang(data.lang)
		// console.log(data.type)
		this.infoData = JSON.stringify(data)
		// console.log(this.infoData)
		if (this.reconnect) {
			this.ws.send(this.infoData);
		} else {
			this.connect()
		}
		// if (this.ws.readyState === WebSocket.OPEN)
	}
	// 关闭
	close() {
		this.reconnect = false
		this.ws.close();
	}
}

export default Websocket;